package com.app.service.impl;


import com.app.model.*;
import com.app.mapper.DividedIntoRecordMapper;
import com.app.service.*;
import com.app.utils.CommonHelp;
import com.app.vo.DividedAdminUserInto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yoominic
 * @since 2024-05-30
 */
@Service
@Slf4j
public class DividedIntoRecordServiceImpl extends ServiceImpl<DividedIntoRecordMapper, DividedIntoRecord> implements IDividedIntoRecordService {


    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private MessageBoxService messageBoxService;

    @Autowired
    private InviteConfigService configService;

    @Autowired
    private UserService userService;

    @Autowired
    private VoucherRecordService voucherRecordService;

    private final static String recordPrefix="CHOUCHNEG";

    /**
     * 按区域代理划分
     *
     * @param totalVoucher  凭证合计
     * @param serialNumber  序列号
     * @param obtainingUser 获得方用户
     * @param type          类型
     * @param consumerUser  消费者用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dividingByRegionalAgent(UserModel consumerUser,UserModel obtainingUser,BigDecimal totalVoucher, String serialNumber, Integer type) {
        DividedIntoRecord dividedIntoRecord = new DividedIntoRecord();
        dividedIntoRecord.setUserId(consumerUser.getId());
        dividedIntoRecord.setCreateTime(LocalDateTime.now());
        dividedIntoRecord.setTotalVoucher(totalVoucher);
        dividedIntoRecord.setSerialNumber(serialNumber);
        dividedIntoRecord.setStatus(1);
        dividedIntoRecord.setType(type);
        BigDecimal cityTotalVoucher = BigDecimal.ZERO;
        BigDecimal areaTotalVoucher = BigDecimal.ZERO;
        BigDecimal plartformVoucher = BigDecimal.ZERO;
        if (obtainingUser == null)
        {
            obtainingUser=consumerUser;
        }
        //寻找收券人的userId
        DividedAdminUserInto adminUserInto = this.adminUserService.queryRegionCurrentUserConsumptionShare(obtainingUser.getCityId(), obtainingUser.getAreaCode());
        if (adminUserInto == null) {
            dividedIntoRecord.setPlartformVoucher(totalVoucher);
            dividedIntoRecord.setStatus(1);
            this.save(dividedIntoRecord);
            return;
        }

        //求出比例
        InviteConfigModel configModel = this.configService.getById(1);
        BigDecimal cityBili = configModel.getCityBili();
        BigDecimal areaBili = configModel.getAreaBili();
        if (adminUserInto.getCityUserId() != null) {
            dividedIntoRecord.setCityUserId(adminUserInto.getCityUserId());
            dividedIntoRecord.setCityId(adminUserInto.getCityId());
            cityTotalVoucher = totalVoucher.multiply(cityBili);

            //给用户分成记录
            UserModel cityUser = this.userService.getById(adminUserInto.getCityUserId());
            if (cityUser != null) {
                cityUser.setVoucher(BigDecimal.valueOf(cityUser.getVoucher()).add(cityTotalVoucher).doubleValue());
                log.info("市级代理分成,{}",cityUser.getVoucher());
                this.userService.updateById(cityUser);

                addMessageBoxRecord(cityUser.getId(),cityTotalVoucher.doubleValue(),1,recordPrefix+serialNumber);
            }
        }
        if (adminUserInto.getAreaUserId() != null) {
            dividedIntoRecord.setAreaUserId(adminUserInto.getAreaUserId());
            dividedIntoRecord.setAreaId(adminUserInto.getAreaId());
            areaTotalVoucher = totalVoucher.multiply(areaBili);
            //给用户分成记录
            UserModel areaUser = this.userService.getById(adminUserInto.getAreaUserId());
            if (areaUser != null) {
                areaUser.setVoucher(BigDecimal.valueOf(areaUser.getVoucher()).add(areaTotalVoucher).doubleValue());

                log.info("区级代理分成,{}",areaUser.getVoucher());

                this.userService.updateById(areaUser);

                addMessageBoxRecord(areaUser.getId(),areaTotalVoucher.doubleValue(),2,recordPrefix+serialNumber);
            }
        }
        plartformVoucher = totalVoucher.subtract(cityTotalVoucher).subtract(areaTotalVoucher);

        dividedIntoRecord.setCityVoucher(cityTotalVoucher.setScale(2, RoundingMode.HALF_UP));
        dividedIntoRecord.setAreaVoucher(areaTotalVoucher.setScale(2, RoundingMode.HALF_UP));
        dividedIntoRecord.setPlartformVoucher(plartformVoucher.setScale(2, RoundingMode.HALF_UP));
        this.save(dividedIntoRecord);

        this.adminUserService.accumulatVoucherForCurrentPlatformUser(1,consumerUser.getId(),"平台用户抽成益联券",plartformVoucher);

    }



    /**
     * 取消抽成通知
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelDrawNotice(Integer userId,String drawnRecordSerialNumber)
    {
        QueryWrapper<VoucherRecordModel> voucherRecordModelQueryWrapper=new QueryWrapper<>();
        voucherRecordModelQueryWrapper.eq("user_id",userId);
        voucherRecordModelQueryWrapper.eq("order_id",drawnRecordSerialNumber);
        this.voucherRecordService.remove(voucherRecordModelQueryWrapper);


        QueryWrapper<MessageBoxModel> messageBoxModelQueryWrapper=new QueryWrapper<>();
        messageBoxModelQueryWrapper.eq("user_id",userId);
        messageBoxModelQueryWrapper.eq("order_sn",drawnRecordSerialNumber);
        this.messageBoxService.remove(messageBoxModelQueryWrapper);
    }








    /**
     * 添加消息框记录
     *
     * @param userId  用户id
     * @param voucher 礼券
     * @param type    类型
     * @param orderSn 订购sn
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMessageBoxRecord(Integer userId,Double voucher,Integer type,String orderSn)
  {
      if(BigDecimal.valueOf(voucher).compareTo(BigDecimal.ZERO)==0)
      {
          return;
      }
      //增加益联券记录
      VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
      voucherRecordModel.setName("抽成奖励通知");
      voucherRecordModel.setTypeName(type==1?"市级抽成":"区级抽成");
      String amountVoucher = "+" + BigDecimal.valueOf(voucher).setScale(2,RoundingMode.HALF_UP) + "券";
      voucherRecordModel.setVoucher(amountVoucher);
      voucherRecordModel.setVoucherType(1);
      voucherRecordModel.setVoucherAmount(BigDecimal.valueOf(voucher).setScale(2,RoundingMode.HALF_UP).doubleValue());
      voucherRecordModel.setUserId(userId);
      voucherRecordModel.setOrderId(orderSn);
      voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
      voucherRecordService.save(voucherRecordModel);


      //消息盒子记录数据
      MessageBoxModel messageBoxModel = new MessageBoxModel();
      messageBoxModel.setUserId(userId);
      messageBoxModel.setQuiltUserId(userId);
      messageBoxModel.setTypeName("抽成通知");
      messageBoxModel.setVoucher(voucher);
      messageBoxModel.setNotes(type==1?"市级代理分成":"区级代理分成");
      messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
      messageBoxModel.setOrderSn(orderSn);
      messageBoxService.save(messageBoxModel);
  }




    /**
     * 按区域代理回滚
     *
     * @param serialNumber 序列号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void RollBackByRegionalAgent(String name,String serialNumber) {
        QueryWrapper<DividedIntoRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("serial_number", serialNumber);
        DividedIntoRecord dividedIntoRecord = this.getOne(queryWrapper);
        if (dividedIntoRecord != null) {
            UserModel cityUser = this.userService.getById(dividedIntoRecord.getCityUserId());
            UserModel areaUser = this.userService.getById(dividedIntoRecord.getAreaUserId());
            if (cityUser != null) {

                if (BigDecimal.valueOf(cityUser.getVoucher()).compareTo(dividedIntoRecord.getCityVoucher()) < 0) {
                    cityUser.setVoucher(BigDecimal.ZERO.doubleValue());
                } else {
                    cityUser.setVoucher(BigDecimal.valueOf(cityUser.getVoucher()).subtract(dividedIntoRecord.getCityVoucher()).doubleValue());
                }
                this.userService.updateById(cityUser);
                cancelDrawNotice(cityUser.getId(),recordPrefix+serialNumber);
            }
            if (areaUser != null) {
                if (BigDecimal.valueOf(areaUser.getVoucher()).compareTo(dividedIntoRecord.getAreaVoucher()) < 0) {
                    areaUser.setVoucher(BigDecimal.ZERO.doubleValue());

                } else {
                    areaUser.setVoucher(BigDecimal.valueOf(areaUser.getVoucher()).subtract(dividedIntoRecord.getAreaVoucher()).doubleValue());
                }
                this.userService.updateById(areaUser);
                cancelDrawNotice(areaUser.getId(),recordPrefix+serialNumber);
            }
            dividedIntoRecord.setStatus(0);
            this.updateById(dividedIntoRecord);


            //回滚平台抽成
            this.adminUserService.accumulatVoucherForCurrentPlatformUser(2,dividedIntoRecord.getUserId(),"用户取消订单平台券回退",dividedIntoRecord.getPlartformVoucher());

        }
    }

    /**
     * 页数
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @param page      第页
     * @param limit     限制
     * @param areaId    区域id
     * @param keyword   关键词
     */
    @Override
    public Object pages(String beginTime, String endTime, Integer page, Integer limit, String areaId, String
            cityId, String keyword,Integer type) {
        Page p = new Page(page, limit);
        IPage<DividedIntoRecord> dividedIntoRecordIPage = this.baseMapper.pages(p, beginTime, endTime, areaId,cityId, keyword,type);
        Map<String, Object> map = new HashMap<>();
        map.put("list", dividedIntoRecordIPage.getRecords());
        map.put("count", dividedIntoRecordIPage.getTotal());
        return map;
    }

    @Override
    public Object dataStatistics(String beginTime, String endTime, String areaId, String
            cityId, String keyword,Integer type) {

        Map<String,Object> dividedIntoRecordIPage = this.baseMapper.dataStatistics( beginTime, endTime, areaId,cityId, keyword,type);

        return dividedIntoRecordIPage;
    }

    @Override
    public BigDecimal queryPlatformDrawing(String startTime, String endTime) {
        return this.baseMapper.queryPlatformDrawing(startTime,endTime);
    }

    /**
     * 查询合计draw平台
     *
     * @return {@link BigDecimal}
     */
    @Override
    public BigDecimal queryTotalDrawPlatform() {
        return this.baseMapper.sumPlatformDrawing();
    }

}
